package com.laymi.common._util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.jfinal.kit.JMap;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

public class SqlUtil {
	public static  Kv searchPage(
			 Model<?> model
			,Map<String, String[]> map
			,String fid
			,Integer pageNumber,Integer pageSize){
		if(fid==null){
			fid="*";
		}
		List<String> list = new ArrayList<String>();
		for(Entry<String, String[]> entry:map.entrySet()){
			String[] ss= entry.getValue();
				if(ss.length==2){//一个条件
					if(ss[0]!=null&&!"".equals(ss[0])){
						if("like".equals(ss[1])){
							list.add(entry.getKey()+" "+ss[1]+" '%"+ss[0]+"%'");
						}else{
							list.add(entry.getKey()+" "+ss[1]+" '"+ss[0]+"'");
						}
					}
			    }else{
			    	if(ss[0]!=null&&!"".equals(ss[0])){
						list.add(entry.getKey()+" "+ss[1]+" '"+ss[0]+"'");
					}
			    	if(ss[2]!=null&&!"".equals(ss[2])){
						list.add(entry.getKey()+" "+ss[3]+" '"+ss[2]+"'");
					}
			    }
	   }
		List<Record> lists = Db.find(model.getSqlPara("search"
				, Kv.by("list", list)
				.set("table", camel2Underline(model.getClass().getSimpleName()))
				.set("pageSize",pageSize)
				.set("pageNumber",(pageNumber-1)*pageSize)
				.set("fid",fid)));
		Long totalRow  = Db.queryLong(model.getSqlPara("searchCount"
				, Kv.by("list", list)
				.set("table", camel2Underline(model.getClass().getSimpleName()))).getSql());
		return  Kv.by("list",lists)
				.set("pageNumber",pageNumber)
				.set("pageSize",pageSize)
				.set("totalRow",totalRow)
				.set("totalPage",(totalRow  +  pageSize  - 1) / pageSize);
	}
	private static String camel2Underline(String line){
        if(line==null||"".equals(line)){
            return "";
        }
        line=String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));
        StringBuffer sb=new StringBuffer();
        Pattern pattern=Pattern.compile("[A-Z]([a-z\\d]+)?");
        Matcher matcher=pattern.matcher(line);
        while(matcher.find()){
            String word=matcher.group();
            sb.append(word.toUpperCase());
            sb.append(matcher.end()==line.length()?"":"_");
        }
        return sb.toString();
    }
}
